<script lang="ts" setup>
import type { VxeGridListeners, VxeTableGridOptions } from '#/adapter/vxe-table'

import { onUnmounted, ref, watch } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import { Alert, Button, Input, message, Space, Switch } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { printTemplateList, printTemplateUpdata } from '#/api/printTemplate'

import popupForm from './popupForm.vue'

const alertTxt = ref('')
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'id',
      label: 'ID',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'name',
      label: '模板名称',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      fieldName: 'cate_id',
      label: '模板类型',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '洗水唛',
            value: 1,
          },
          {
            label: '合格证',
            value: 2,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'auth_type',
      label: '权限范围',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '指定',
            value: 1,
          },
          {
            label: '全部',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: '状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '开启',
            value: 1,
          },
          {
            label: '关闭',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'mark',
      label: '模板备注',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'tpl_url',
      label: '下载地址',
      operator: 'LIKE',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    trigger: 'row',
  },

  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    { title: 'ID', field: 'id', align: 'center', width: 100 },
    { title: '模板名称', field: 'name', align: 'center', width: 300 },
    { title: '图片', field: 'image', align: 'center', cellRender: { name: 'CellImage' } },
    {
      title: '模板类型',
      field: 'cate_id',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          { color: 'blue', label: '洗水唛', value: 1 },
          { color: 'success', label: '合格证', value: 2 },
        ],
      },
    },
    { title: '状态', field: 'status', align: 'center', slots: { default: 'status' } },
    {
      title: '权限范围',
      field: 'auth_type',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          { color: 'blue', label: '指定', value: 1 },
          { color: 'success', label: '全部', value: 0 },
        ],
      },
    },
    { title: '权限列表', field: 'auth_names', align: 'center', width: 300 },
    { title: '排除权限', field: 'exclude_auths', align: 'center', width: 100 },
    { title: '下载模板', field: 'tpl_url', align: 'center', slots: { default: 'tpl_url' } },
    { title: '宽度（mm）', field: 'width', align: 'center' },
    { title: '高度（mm）', field: 'height', align: 'center' },
    { title: '模板备注', field: 'mark', align: 'center' },
    { title: '操作', field: 'action', fixed: 'right', width: 150, slots: { default: 'action' } },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await printTemplateList({
          page: page.currentPage,
          limit: page.pageSize,
          quick_search: quick_search.value,
          search,
        })
        alertTxt.value = res.remark
        res.list.forEach((row: any) => {
          row.status = row.status === 1
        })
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },

  id: 'printTemplate',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
}

// 双击打开编辑
const gridEvents: VxeGridListeners = {
  cellDblclick: ({ row }) => {
    openEdit(row.id, 'edit')
  },
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
})

//  按钮的禁用状态
const isDisabled = ref(true)
// 检查并更新拷贝按钮状态
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
    } else {
      isDisabled.value = true
    }
  } catch {
    isDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)

function modelClose() {
  gridApi.reload()
}

const [formModal, formModalApi] = useVbenModal({
  connectedComponent: popupForm,
})
// 编辑
function openEdit(res: any, but: any) {
  formModalApi.setData({ rowData: res, view: but }).open()
}
function openEdits() {
  const selectedRecords = gridApi.grid.getCheckboxRecords()
  if (selectedRecords.length === 0) {
    message.error('请选择数据')
    return
  }
  const data = selectedRecords.map((record: any) => record.id)
  formModalApi.setData({ rowData: data, view: 'edit' }).open()
}

/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}

function changeSwitch(val: any, row: any) {
  const params = { status: val ? 1 : 0, id: row.id }
  printTemplateUpdata(params).then((res: any) => {
    if (res.data.code === 1) {
      message.success(res.data.msg)
    } else {
      message.error(res.data.msg)
    }
  })
}

const copyText = (fileUrl: string) => {
  const input = document.createElement('input')
  input.value = fileUrl // 替换为你需要复制的内容
  document.body.append(input)
  input.select()
  document.execCommand('copy')
  input.remove()
  message.success('复制成功')
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openEdit('', 'add')">新建</Button>
            <Button type="primary" @click="openEdits" :disabled="isDisabled">编辑</Button>
            <Alert type="warning" closable show-icon>
              <template #message>
                <span v-html="alertTxt"></span>
              </template>
            </Alert>
          </Space>
        </div>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通过模板名称模糊搜索" style="width: 300px; margin-right: 8px" @change="doSearch" />
      </template>

      <template #status="{ row }">
        <Switch v-model:checked="row.status" @change="(val) => changeSwitch(val, row)" />
      </template>

      <template #tpl_url="{ row }">
        <Button :title="row.tpl_url" size="small" @click="copyText(row.tpl_url)">复制</Button>
      </template>

      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <Button type="primary" size="small" @click="openEdit(row.id, 'edit')"> 编辑 </Button>
        </Space>
      </template>
    </Grid>
    <formModal @refresh="modelClose()" />
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
